import cs from 'classnames'
import { useContext, useEffect, useMemo, useState } from 'react'
import { Redirect, Route, Switch } from 'react-router-dom'
import { useLocation } from 'react-router-dom'

import Header from './components/Header'
import { Log } from './components/log'
import { GlobalContext } from './context'
import routes from './routes'
import lazyload from './utils/lazyload'

/**
 * 获取扁平化的路由数组
 * @param routes 路由配置数组
 * @returns 扁平化的路由数组
 */

const getFlattenRoutes = (routes) => {
  return routes.reduce((arr = [], route) => {
    return arr.concat([{ ...route }], getFlattenRoutes(route.children || []))
  }, [])
}

function PageLayout() {
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const flattenRoutes = useMemo(() => getFlattenRoutes(routes) || [], [routes])
  const { rtl } = useContext(GlobalContext)

  const location = useLocation()

  const [pathname, setPathname] = useState('/')
  useEffect(() => {
    setPathname(location.pathname)
  }, [location])
  return (
    <div>
      <Header show={pathname != '/'} />
      {/* <Log /> */}
      <Switch>
        {console.table(flattenRoutes)}
        {flattenRoutes.map((route, index) => {
          const routeDom = route.redirect ? (
            <Route exact key={index} path={`${route.key}`}>
              <Redirect to={`/${route.redirect}`} />
            </Route>
          ) : (
            <Route key={index} path={`${route.key}`} component={route.component} />
          )
          return routeDom
        })}
        <Route path="*" component={lazyload(() => import('./pages/403'))} />
      </Switch>
    </div>
  )
}
export default PageLayout
